package com.mjk.common.tools.conver.abstractor;


import com.mjk.common.tools.conver.IConver;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.tools.scheduled.DynamicScheduledHandler;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.*;
/**
 * 带定时任务的转化任务
 * @author jafek
 *
 */
public abstract class SchedledConver extends DynamicScheduledHandler implements IConver {
	
	private static final Integer MAX_POOL_SIZE = 10;
	
	private static final Integer MAX_QUERE_NUMBER = 5000;
	
	private boolean running = false;
		
	protected SchedledConver(){
		running = true;	
		init();
	}
	/**
	 * 队列
	 */
	protected  final BlockingQueue<Object> queue=new ArrayBlockingQueue<>(MAX_QUERE_NUMBER);
	/**
	 * 线程池
	 */
	private  final ExecutorService pool=Executors.newFixedThreadPool(MAX_POOL_SIZE, new CustomizableThreadFactory("DefaultConver"));
	
			
	@PostConstruct
	public void init() {
		pool.execute(()->{
			while(running){
				try{
					converTarget(queue.take());
				}catch(InterruptedException e){
					Thread.currentThread().interrupt();
				}
			}
		});
	}

	@PreDestroy
	public void destroy() throws InterruptedException {		
		running = false;
		pool.shutdown();
		if (!pool.awaitTermination(5L, TimeUnit.SECONDS)) {
			BizLogger.warn("......AnsyTaskExecute: Exceed max timeout for waiting shutdown, ready force close pool.");
			pool.shutdownNow();
		}
	}
}
